package com.xumt.hwHMSdemo;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

import com.xumt.hwHMSdemo.cannectSb.HttpRequest;
import com.xumt.hwHMSdemo.ui.PersonFragment;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Showaddress extends AppCompatActivity {
    private String result;
   private List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
   private SimpleAdapter adapter= null;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_showaddress);
//        refresh();
//        finish();
//        startActivity(getIntent());
        onResume();

        adapter = new MySimpleAdapter(this, getData(), R.layout.mylist,new String[]{"name","phone","address"},
                new int[]{R.id.name,R.id.phone,R.id.address});
        ListView listView = (ListView) findViewById(R.id.addresslist);
        listView.setAdapter(adapter);
//        setListAdapter(adapter);
        Intent intent=new Intent(Showaddress.this,Addaddress.class);

        Button button=(Button)findViewById(R.id.setaddress);

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(intent);
            }
        });


    }


    private class MySimpleAdapter extends SimpleAdapter {

        public MySimpleAdapter(Context context,
                               List<? extends Map<String, ?>> data, int resource,
                               String[] from, int[] to) {
            super(context, data, resource, from, to);
            // TODO Auto-generated constructor stub
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            // TODO Auto-generated method stub
            final int mPosition = position;
            convertView = super.getView(position, convertView, parent);
            Button moren=(Button) convertView
                    .findViewById(R.id.moren);
            Button buttonDelete = (Button) convertView
                    .findViewById(R.id.delete);
            Button buttonmodify=(Button) convertView
                    .findViewById(R.id.modify);
            try {
                JSONArray jsonArray = new JSONArray(result);
                JSONObject jsonObject = jsonArray.getJSONObject(mPosition);
                if(jsonObject.getInt("moren")==0)moren.setVisibility(View.GONE);
                else moren.setVisibility(View.VISIBLE);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            buttonDelete.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub
                    try {
                        JSONArray jsonArray = new JSONArray(result);
                        JSONObject jsonObject = jsonArray.getJSONObject(mPosition);
                        delete(jsonObject.getInt("id"));
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
//                    Toast.makeText(Showaddress.this,"已下發",Toast.LENGTH_SHORT).show();
                    Log.i("haha","位置"+mPosition);
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    refresh();
                }
            });

            buttonmodify.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub
                    try {
                        JSONArray jsonArray = new JSONArray(result);
                        JSONObject jsonObject = jsonArray.getJSONObject(mPosition);
//                        int i=jsonObject.getInt("id");
//                        Map<String, Object>map=list.get(mPosition);
//                        for(int j=0;j<list.size();j++)
//                        {
//                            if(i==(int)list.get(mPosition).get("id"))
//                            {
//                                map.put("moren",1 );
//                                list.set(mPosition, map);//替换listItems中原来的map
//                            }
//                            else {
//                                map.put("moren",0 );
//                                list.set(mPosition, map);//替换listItems中原来的map
//                            }
//
//
//                        }
                        modify(jsonObject.getInt("id"));
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
//                    Toast.makeText(Showaddress.this,"已下發",Toast.LENGTH_SHORT).show();
                    Log.i("haha","位置"+mPosition);
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    refresh();
                }
            });
            return convertView;
        }

//        private Handler mHandler = new Handler() {
//
//            @Override
//            public void handleMessage(Message msg) {
//                // TODO Auto-generated method stub
//                super.handleMessage(msg);
//                switch (msg.what) {
//                    case BUTTON_ADD:
//                        HashMap<String, Object> map = new HashMap<String, Object>();
//                        mList.add(map);
//                        notifyDataSetChanged();// 这个函数很重要，告诉Listview适配器数据发生了变化
//                        mShowInfo.setText("你点击了第" + (msg.arg1 + 1) + "按钮");
//                        break;
//                    case BUTTON_DELETE:
//                        mList.remove(msg.arg1);
//                        notifyDataSetChanged();
//                        mShowInfo.setText("你删除了第" + (msg.arg1 + 1) + "行");
//                        break;
//                }
//            }
//
//        };

    }

    private List<Map<String, Object>> getData()  {
        new Thread() {
            public void run() {
                try {
                    HttpRequest request = new HttpRequest();
                    result = request.sendGet("http://169.254.67.221:8081/address/findaddress",
                            "username="+Login2.usernamen  );
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }.start();

        try {
            Thread.sleep(2000);
            JSONArray jsonArray = new JSONArray(result);
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("name", "收货人："+jsonObject.getString("name"));
                map.put("phone", "联系电话："+jsonObject.getString("phone"));
                map.put("address", "收货地址："+jsonObject.getString("address"));
                map.put("moren",jsonObject.getInt("moren"));
                list.add(map);

            }
        } catch (JSONException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return list;
    }

    private void delete(int id){
        new Thread() {
            public void run() {
                try {
                    HttpRequest request = new HttpRequest();
                    request.sendGet("http://169.254.67.221:8081/address/delete",
                            "id="+id );
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }

    private void modify(int addressid){
        new Thread() {
            public void run() {
                try {
                    HttpRequest request = new HttpRequest();
                    request.sendGet("http://169.254.67.221:8081/address/modify",
                            "username="+Login2.usernamen+"&"+"addressid="+addressid );
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }

    public void refresh() {
        finish();
        Intent intent = new Intent(Showaddress.this, Showaddress.class);
        startActivity(intent);
    }
}